import { getLayoutByDagre } from "../utils";
import { produce } from "immer";

export const useLayout = () => {
  const organize = (nodes, edges, setNodes) => {
    const layout = getLayoutByDagre(nodes, edges);
    console.log(layout);
    const rankMap = {} as Record<string, Node>;
    nodes.forEach((node) => {
      const rank = layout.node(node.id).rank!;

      if (!rankMap[rank]) {
        rankMap[rank] = node;
      } else {
        if (rankMap[rank].position.y > node.position.y) rankMap[rank] = node;
      }
    });

    const newNodes = produce(nodes, (draft) => {
      draft.forEach((node) => {
        const nodeWithPosition = layout.node(node.id);

        node.position = {
          x: nodeWithPosition.x - node.width! / 2,
          y:
            nodeWithPosition.y -
            node.height! / 2 +
            rankMap[nodeWithPosition.rank!].height! / 2,
        };
      });
    });

    setNodes(newNodes);
  };

  return {
    organize,
  };
};
